package com.ikingtech.framework.sdk.job.embedded.caller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.enums.common.FrameworkServerFeedbackTypeEnum;
import com.ikingtech.framework.sdk.job.model.rpc.JobExecuteInfo;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.support.server.FrameworkServerFeedbackCaller;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;

import static com.ikingtech.framework.sdk.context.constant.SecurityConstants.*;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class JobServerFeedbackCaller implements FrameworkServerFeedbackCaller {

    private final LoadBalancerClient loadBalancerClient;

    @Override
    public R<Object> call(Object data) {
        JobExecuteInfo job = (JobExecuteInfo)data;
        ServiceInstance client = this.loadBalancerClient.choose(job.getExecutorClientId());
        try {
            String resultStr = Tools.Http.post(Tools.Http.SCHEMA_HTTP + client.getHost() + ":" + client.getPort() + "/job/resolve", Tools.Json.toJsonStr(job), Tools.Coll.newMap(Tools.Coll.Kv.of("Authorization", GLOBAL_TOKEN), Tools.Coll.Kv.of(HEADER_TENANT_CODE, DEFAULT_TENANT_CODE)));
            return Tools.Json.toBean(resultStr, new TypeReference<>() {
            });
        } catch (Exception e) {
            return R.failed();
        }
    }

    @Override
    public FrameworkServerFeedbackTypeEnum type() {
        return FrameworkServerFeedbackTypeEnum.JOB_FEEDBACK;
    }
}
